#include <iostream>
#include <string>
#include <sys/poll.h>
#include "easysock.hpp"

namespace server
{

const int gsize = 20;

class poll_server : public inet::tcp::server
{
public:
    poll_server(int port) : server(port), _polls(new struct pollfd[gsize]), _size(0) 
    {
    }

    ~poll_server() {}

    void start()
    {
        _polls[0].fd = _sock;
        _polls[0].events = POLLIN;
        ++_size;

        while (true)
        {
            if (poll(_polls.get(), _size, -1) > 0)
            {
                for (int i = 0; i < _size; i++)
                {
                    if (_polls[i].revents & POLLIN)
                    {
                        if (_polls[i].fd == _sock)
                        {
                            int sock = accept();
                            _polls[_size].fd = sock;
                            _polls[_size].events = POLLIN;
                            ++_size;
                        }
                        else
                        {
                            std::string buf;
                            ssize_t s = recv(_polls[i].fd, &buf, 1024);
                            
                            if (s > 0) send(_polls[i].fd, "server return >>> " + buf);
                            else break;
                        }
                    }
                }
            }
        }
    }

private:
    std::unique_ptr<struct pollfd[]> _polls;
    int _size;
};

}
